package com.lc1993929.servlet;

import com.lc1993929.util.WechatController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by LiuChang on 2017/5/4.
 */
public class WechatIoServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置接口的数据格式和编码方式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        //读取微信客户端post发送过来的数据
        InputStream inputStream = req.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String string = "";
        StringBuffer stringBuffer = new StringBuffer();

        //按行读取内容
        while (null != (string = bufferedReader.readLine())) {
            stringBuffer.append(string);
        }

        String content = stringBuffer.toString();

        //调用微信处理流程，获取处理结果
        String result = new WechatController().wechatProcess(content);


        //返回处理完成的结果
        OutputStream os = resp.getOutputStream();
        os.write(result.getBytes("UTF-8"));
        os.flush();
        os.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
